package com.imooc.log.utils;

import cz.mallat.uasparser.OnlineUpdater;
import cz.mallat.uasparser.UASparser;
import org.apache.commons.lang3.StringUtils;
import com.imooc.log.domain.UserAgentInfo;

import java.io.IOException;

/**
 * UserAgent解析工具类
 */
public class UAUtils {

    public static UASparser parser = null;

    static {
        try {
            parser = new UASparser(OnlineUpdater.getVendoredInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将官方解析出来的UserAgentInfo转成我们自己需要的UserAgentInfo
     * 其实就是需要的字段做了转换
     * @param ua
     * @return
     */
    public static UserAgentInfo getUserAgentInfo(String ua) {
        UserAgentInfo info = null;
        try {
            if (StringUtils.isNotEmpty(ua)) {
                cz.mallat.uasparser.UserAgentInfo tmp = parser.parse(ua);
                if (null != tmp) {
                    info = new UserAgentInfo();
                    info.setBrowserName(tmp.getUaFamily());
                    info.setBrowserVersion(tmp.getBrowserVersionInfo());
                    info.setOsName(tmp.getOsFamily());
                    info.setOsVersion(tmp.getOsName());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

    public static void main(String[] args) throws IOException {
//        UASparser parser = new UASparser(OnlineUpdater.getVendoredInputStream());
//        UserAgentInfo info = parser.parse("Mozilla/4.0 (compatible; MSIE 7.0;Windows NT 5.1; )");

        UserAgentInfo info = UAUtils.getUserAgentInfo("Mozilla/4.0 (compatible; MSIE 7.0;Windows NT 5.1; )");
        System.out.println(info);
    }
}
